//
//  StepCountViewController.m
//  Health
//
//  Created by LeeJay on 16/8/29.
//  Copyright © 2016年 LeeJay. All rights reserved.
//

#import "StepCountViewController.h"
#import "HKHealthStore+Extension.h"
#import "StepCountModel.h"
#import "NSDate+Extension.h"

@interface StepCountViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *dataSoure;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation StepCountViewController

- (NSMutableArray *)dataSoure
{
    if (!_dataSoure) {
        _dataSoure = [NSMutableArray array];
    }
    return _dataSoure;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.tableFooterView = [UIView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.view addSubview:self.tableView];

    NSDate *end = [NSDate date];

    NSDate *start = [NSDate getTodayAgoWithDays:30];
    
    __weak typeof(self) weakSelf = self;
    
    [self.healthStore getStepCountStartDate:start
                                    endDate:end
                                    success:^(NSArray *results) {
                                        
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            weakSelf.dataSoure = [NSMutableArray arrayWithArray:results];
                                            [weakSelf.tableView reloadData];
                                        });
                                        
                                    } failure:^(NSError *error) {
                                        
                                    }];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSoure.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }
    StepCountModel *model = self.dataSoure[indexPath.row];
    cell.textLabel.text = [model.startDate substringToIndex:10];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%zd步",model.stepCount];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"一个月的步数";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
